package com.plugin.test

import com.android.build.gradle.internal.dsl.BaseAppModuleExtension
import org.gradle.api.Plugin
import org.gradle.api.Project
import java.io.File
import java.text.SimpleDateFormat
import java.util.*

class ApkRenamePlugin: Plugin<Project> {
    override fun apply(project: Project) {
        val android = project.extensions.getByType(BaseAppModuleExtension::class.java)
        android.applicationVariants.all {
            val variant = this
            val outputFileDir = if (variant.flavorName.isNotBlank()) {
                "${project.buildDir}/apk/${variant.buildType.name}/${variant.flavorName}/${this.versionName}"
            } else {
                "${project.buildDir}/apk/${variant.buildType.name}/${this.versionName}"
            }
            val sdf = SimpleDateFormat("yyyyMMdd_HH")
            val date = sdf.format(Date())
            this.outputs.forEach {
                if (it is com.android.build.gradle.internal.api.ApkVariantOutputImpl) {
                    if (variant.flavorName.isNullOrBlank() || variant.flavorName.equals("null", true)) {
                        it.outputFileName =
                            "${project.projectDir.name}_${variant.buildType.name}_${date}_v${variant.versionName}.${variant.versionCode}.apk"
                    } else {
                        it.outputFileName =
                            "${project.projectDir.name}_${flavorName}_${variant.buildType.name}_${date}_v${variant.versionName}.${variant.versionCode}.apk"
                    }
                }
            }

            assembleProvider.get().doLast {
                val out = File(outputFileDir)
                try {
                    project.copy {
                        from(mappingFileProvider.get())
                        into(out)
                        rename {
                            if (variant.flavorName.isNullOrBlank() || variant.flavorName.equals("null", true)) {
                                "${variant.buildType.name}-mapping-${variant.versionName}.txt"
                            } else {
                                "${variant.buildType.name}-${variant.flavorName}-mapping-${variant.versionName}.txt"
                            }
                        }
                    }
                } catch (e: Exception) {
                    println("Copy mapping file failed:" + e.message)
                }

                variant.outputs.forEach { file ->
                    project.copy {
                        from(file.outputFile)
                        into(out)
                    }
                }
            }
        }
    }
}